<?php
/**
 * master unit test controller only responsible for restoring testing database each it runs
 */
class master_unit_test extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        // switch to unit test database from production database
        $dsn = 'mysql://root:c3603896@localhost/unit_test_yun';
        $this->load->database($dsn);
    }

    public function index()
    {
        // reset testing databae every time it runs, no manual operation on database needed, and more consistant
        $this->load->dbforge();
        $this->dbforge->drop_database('unit_test_yun');
        $this->dbforge->create_database('unit_test_yun');

        // script from http://dan.cx/blog/2006/12/restore-mysql-dump-using-php
        // restore database with default file
        // Name of the file
        $filename = 'unit_test_yun.sql';
        // MySQL host
        $mysql_host = 'localhost';
        // MySQL username
        $mysql_username = 'root';
        // MySQL password
        $mysql_password = 'c3603896';
        // Database name
        $mysql_database = 'unit_test_yun';

        //////////////////////////////////////////////////////////////////////////////////////////////

        // Connect to MySQL server
        mysql_connect($mysql_host, $mysql_username, $mysql_password) or die('Error connecting to MySQL server: ' . mysql_error());
        // Select database
        mysql_select_db($mysql_database) or die('Error selecting MySQL database: ' . mysql_error());

        // Temporary variable, used to store current query
        $templine = '';
        // Read in entire file
        $lines = file($filename);
        // Loop through each line
        foreach ($lines as $line)
        {
            // Skip it if it's a comment
            if (substr($line, 0, 2) == '--' || $line == '')
                continue;

            // Add this line to the current segment
            $templine .= $line;
            // If it has a semicolon at the end, it's the end of the query
            if (substr(trim($line), -1, 1) == ';')
            {
                // Perform the query
                mysql_query($templine) or print('Error performing query \'<strong>' . $templine . '\': ' . mysql_error() . '<br /><br />');
                // Reset temp variable to empty
                $templine = '';
            }
        }

        // setup view page
        $data = array(
						'page_title' => 'test, test, test',
						'page_css'   => array(),
						'page_js'    => array()
					);
		$this->load->view('unit_test', $data);
    }
}